package com.javasm.controller.JINXIAOController;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javasm.commons.basic.BaseController;
import com.javasm.commons.entity.AxiosResult;
import com.javasm.commons.enums.E;
import com.javasm.commons.exception.MvcException;
import com.javasm.commons.interceptors.LoginInterceptor;
import com.javasm.dto.SysUserDto;
import com.javasm.entity.JINXIAOEntity.SysUser;
import com.javasm.service.JINXIAOService.SysUserService;
import com.javasm.util.JWTUtil;
import com.javasm.util.RequestServletUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("sysUser")
public class SysUserController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(SysUserController.class);
    @Resource
    private SysUserService sysUserService;

    @Resource
    private RequestServletUtil requestServletUtil;


    @PostMapping("login")
    public ResponseEntity login(@RequestBody SysUser u, HttpSession session){
        SysUser queryUser = sysUserService.getUserByName(u.getUname());
        logger.info("queryUser:",queryUser);
        if(queryUser==null)throw new MvcException(E.NOT_EXISTS);
        if(!u.getUpwd().equals(queryUser.getUpwd()))throw new MvcException(E.PWD_ERROR);
//        session.setAttribute("LOGIN_USER",queryUser);
        //生成token,通过响应头发送至客户端
        String jwt = JWTUtil.generateLoginToken(queryUser.getUphone());
        queryUser.setUpwd("");
        //将token放在请求头发送给客户端
        HttpHeaders h  = new HttpHeaders();
        h.add("admin_token",jwt);
        //登录日志记录.
        //签到,给奖励.
        //自动登录.
//        ReturnEntity re = new ReturnEntity();
//        re.setReturnCode(AxiosResult.suc().getCode());
//        re.setReturnMsg(AxiosResult.suc().getMsg());
        AxiosResult suc = AxiosResult.suc(queryUser);
        return new ResponseEntity(suc,h, HttpStatus.OK);
    }

    @GetMapping("/valicode")
    public AxiosResult getValicode(@RequestParam String loginPhone){
        sysUserService.sendValicode(loginPhone);
        return AxiosResult.suc();
    }


    @PostMapping("/checkValicode")
    public AxiosResult phoneLogin(@RequestBody SysUserDto sysUserDto){ //登录获取验证码
        //1. 先比较验证码
        boolean isok = sysUserService.checkValicode(sysUserDto.getUphone(),sysUserDto.getCode());
        //2.根据手机号用户信息
        if(!isok)throw new MvcException(E.VALICODE_ERROR);
        SysUser loginUser = sysUserService.getUserByPhone(sysUserDto.getUphone());
        //3.获取不到,未注册.
        if(loginUser==null)throw new MvcException(E.PHONE_NOT_EXITS);
        //4.去缓存获取到用户信息,表示登录
        requestServletUtil.getSession().setAttribute("LOGIN_USER",loginUser);
        return AxiosResult.suc();
    }
    @PostMapping("/getLoginSysUser")
    public AxiosResult getLoginSysUser(){
        // 对于修改删除操作，获取当前操作人员信息， ThreadLocal中获取用户的标识
        SysUser sysUser = LoginInterceptor.getLoginUser();
        return AxiosResult.suc(sysUser);
    }


    @PostMapping("logout")
    public AxiosResult logout(){
        System.out.println("logout");
        return AxiosResult.suc();
    }

  
     @GetMapping("{id}")
    public AxiosResult selectById(@PathVariable Integer id)
    {
        logger.info("selectById:{}",id);
        SysUser obj = this.sysUserService.queryById(id);
        return suc(obj);
    }
    
    @GetMapping("ids/{ids}")
    public AxiosResult selectListByIds(@PathVariable String ids)
    {
        String[] idsArray = ids.split(",");
        logger.info("selectListByIds:{}",idsArray);
        List<SysUser> list = this.sysUserService.queryByIds(Arrays.asList(idsArray));
        return suc(list);
    }

    @GetMapping("list")
    @SuppressWarnings("unchecked")//List没有使用泛型， .@SuppressWarnings("unchecked") 隐藏所有的不安全的警告信息
    public AxiosResult selectList(SysUser obj, Integer pageNum, Integer pageSize)
    {

        if(pageNum==null) pageNum=1;
        if(pageSize==null) pageSize=10;
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> list = this.sysUserService.queryUserAndDeptList(obj);
        logger.info("list:{}",list);
        PageInfo i = new PageInfo(list);
        return suc(i);
    }

    @PostMapping
    public AxiosResult add(@RequestBody SysUser obj)
    {
        // 对于修改删除操作，获取当前操作人员信息， ThreadLocal中获取用户的标识
        SysUser sysUser = LoginInterceptor.getLoginUser();
        obj.setUpdateBy(sysUser.getUname());
        Boolean r = this.sysUserService.insert(obj);
        return isok(r);
    }

    @PutMapping
    public AxiosResult update(@RequestBody SysUser obj)
    {
        // 对于修改删除操作，获取当前操作人员信息， ThreadLocal中获取用户的标识
        SysUser sysUser = LoginInterceptor.getLoginUser();
        obj.setUpdateBy(sysUser.getUname());
        Boolean r = this.sysUserService.update(obj);
        return isok(r);
    }

    @DeleteMapping("{ids}")
    public AxiosResult delByIds(@PathVariable String ids)
    {
        String[] idsArray = ids.split(",");
        Boolean r = this.sysUserService.deleteByIds(Arrays.asList(idsArray));
        return isok(r);
    }
    //获取登录验证吗
    @GetMapping("getSendImgCode")
    public AxiosResult getSendImgCode(){
        LineCaptcha captcha= CaptchaUtil.createLineCaptcha(155,45,4,100);
        String code = captcha.getCode();
        String img = captcha.getImageBase64();
        Map map = new HashMap();
        map.put("code",code);
        map.put("ImageBase64",img);
        return AxiosResult.suc();
    }

    //生成验证码图片
    public static void main(String[] args) {
        try {
            LineCaptcha captcha= CaptchaUtil.createLineCaptcha(155,45,4,100);
            String code = captcha.getCode();
            String img = captcha.getImageBase64();
            FileOutputStream fos = new FileOutputStream("D:\\img.jpg");
            fos.write(img.getBytes());
            fos.close();
            System.out.println(code);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}